package com.igfd.tanmao.service.impl;

import com.igfd.tanmao.mapper.TanmaoItemMapper;
import com.igfd.tanmao.mapper.TanmaoOrderDetailMapper;
import com.igfd.tanmao.mapper.TanmaoOrderMapper;
import com.igfd.tanmao.mapper.UniqueCodeProductMapper;
import com.igfd.tanmao.pojo.*;
import com.igfd.tanmao.service.ItemsService;
import com.igfd.tanmao.utils.CommonUtils;
import com.igfd.tanmao.utils.JsonUtils;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Item;
import com.taobao.api.domain.Sku;
import com.taobao.api.request.*;
import com.taobao.api.response.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service(value = "itemsService")
public class ItemsServiceImpl implements ItemsService {

    @Autowired
    private TanmaoItemMapper tanmaoItemMapper;

    @Autowired
    private TanmaoOrderDetailMapper tanmaoOrderDetailMapper;

    @Autowired
    private TanmaoOrderMapper tanmaoOrderMapper;

    @Autowired
    private UniqueCodeProductMapper uniqueCodeProductMapper;

    @Override
    public ItemsOnsaleGetResponse getTanmaoItemsOnsale(String sessionKey,Long currentPage,Long pageSize) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(CommonUtils.SERVERURL, CommonUtils.APPKEY, CommonUtils.APPSECRET);
        ItemsOnsaleGetRequest req = new ItemsOnsaleGetRequest();
        req.setFields("num_iid,pic_url,title");
        req.setPageNo(currentPage);
        req.setPageSize(pageSize);
        ItemsOnsaleGetResponse rsp = client.execute(req, sessionKey);

        return rsp;
    }

    @Override
    public ItemsInventoryGetResponse getTanmaoItemsInventory(String sessionKey,Long currentPage,Long pageSize) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(CommonUtils.SERVERURL, CommonUtils.APPKEY, CommonUtils.APPSECRET);
        ItemsInventoryGetRequest req = new ItemsInventoryGetRequest();
        req.setFields("num_iid,pic_url,title");
        req.setPageNo(currentPage);
        req.setPageSize(pageSize);
        ItemsInventoryGetResponse rsp = client.execute(req, sessionKey);

        return rsp;
    }

    @Override
    public void addTanmaoItemsOnsaleToErp(String sessionKey) throws ApiException {
        List<Item> itemList = new ArrayList<>();

        long currentPage = 1;
        long totalPage = 1;
        long pageSize = 200;

        while (currentPage <= totalPage) {
            ItemsOnsaleGetResponse rsp = this.getTanmaoItemsOnsale(sessionKey,currentPage,pageSize);

            itemList.addAll(rsp.getItems());
            long l = rsp.getTotalResults();
            if (currentPage == 1) {
                totalPage = (long) Math.ceil((l * 1.0) / pageSize);
            }

            currentPage++;
        }

        long currentPageI = 1;
        long totalPageI = 1;
        long pageSizeI = 200;

        while (currentPageI <= totalPageI) {
            ItemsInventoryGetResponse rsp = this.getTanmaoItemsInventory(sessionKey, currentPageI, pageSizeI);

            itemList.addAll(rsp.getItems());
            long l = rsp.getTotalResults();
            if (currentPageI == 1) {
                totalPageI = (long) Math.ceil((l * 1.0) / pageSizeI);
            }

            currentPageI++;
        }

        List<List<Object>> rows = new ArrayList();

        for (Item item : itemList) {
            ItemSkusGetResponse tanmaoItemSkus = this.getTanmaoItemSkus(String.valueOf(item.getNumIid()), sessionKey);
            List<Sku> skus = tanmaoItemSkus.getSkus();

            for (Sku sku : skus) {
                TanmaoItem tanmaoItem = tanmaoItemMapper.findTanmaoItemByNumiidAndSkuid(String.valueOf(item.getNumIid()), String.valueOf(sku.getSkuId()));
                if (tanmaoItem == null) {
                    tanmaoItemMapper.add(String.valueOf(item.getNumIid()),String.valueOf(sku.getSkuId()),sku.getPropertiesName(),new Date());
                }
            }
        }

        /*long currentPage = 1;
        long totalPage = 1;
        long pageSize = 200;

        ArrayList<String> numIids = new ArrayList<String>();

        while (currentPage <= totalPage) {
            ItemsOnsaleGetResponse rsp = this.getTanmaoItemsOnsale(sessionKey,currentPage,pageSize);

            long l = JsonUtils.parseTanmaoItemsOnsaleRsp(rsp.getBody(), numIids);
            if (currentPage == 1) {
                totalPage = (long) Math.ceil((l * 1.0) / pageSize);
            }

            currentPage++;
        }

        for (String numIid:
                numIids) {
            ItemSkusGetResponse tisRsp = this.getTanmaoItemSkus(numIid, sessionKey);
            ArrayList<Map<String, String>> mapArrayList = JsonUtils.parseTanmaoItemSkusRsp(tisRsp.getBody());

            for (Map<String, String> skuItem : mapArrayList) {

                String propertiesName = skuItem.get("propertiesName");
                String skuId = skuItem.get("skuId");

                TanmaoItem tanmaoItem = tanmaoItemMapper.findTanmaoItemByNumiidAndSkuid(numIid, skuId);
                if (tanmaoItem == null) {
                    tanmaoItemMapper.add(numIid,skuId,propertiesName,new Date());
                }
            }
        }*/
    }

    @Override
    public ItemSkusGetResponse getTanmaoItemSkus(String numIids, String sessionKey) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(CommonUtils.SERVERURL, CommonUtils.APPKEY, CommonUtils.APPSECRET);
        ItemSkusGetRequest req = new ItemSkusGetRequest();
        req.setFields("sku_id,num_iid,quantity,properties_name,price");
        req.setNumIids(numIids);
        ItemSkusGetResponse rsp = client.execute(req, sessionKey);

        return rsp;
    }

    @Override
    public void getTanmaoTradesSoldGet(String orderStatus,Long currentPage,String sessionKey) throws ApiException {

        TaobaoClient client = new DefaultTaobaoClient(CommonUtils.SERVERURL, CommonUtils.APPKEY, CommonUtils.APPSECRET);
        TradesSoldGetRequest req = new TradesSoldGetRequest();
        req.setFields("tid,status,created,pay_time,receiver_name,receiver_state,receiver_address,receiver_mobile,orders");
        req.setStatus(orderStatus);
        req.setUseHasNext(true);
        req.setPageNo(currentPage);

        TradesSoldGetResponse rsp = client.execute(req, sessionKey);
        TanmaoTradesSoldGetResult tanmaoTradesSoldGetResult = JsonUtils.parseTanmaoOrderInfoRsp(rsp.getBody());

        ArrayList<TanmaoOrderResult> orderList = tanmaoTradesSoldGetResult.getOrder();

        if (orderList != null) {
            Iterator<TanmaoOrderResult> iterator = orderList.iterator();
            while (iterator.hasNext()) {
                TanmaoOrderResult orderInfo = iterator.next();

                ArrayList<TanmaoOrderDetailResult> orderDetailList = orderInfo.getOrders();

                int totalQuantity = 0;
                double totalFee = 0;
                double totalPayment = 0;
                double totalDiscountFee = 0;
                double totalAdjustFee = 0;

                for (TanmaoOrderDetailResult orderDetail: orderDetailList) {

                    int detailCount = tanmaoOrderDetailMapper.findTanmaoOrderDetailCount(orderInfo.getTid(), orderDetail.getOid(), orderDetail.getNumIid(), orderDetail.getSkuId());

                    if (detailCount == 0) {
                        totalQuantity = totalQuantity + Integer.valueOf(orderDetail.getTotalQuantity());
                        totalFee = totalFee + Double.valueOf(orderDetail.getTotalFee());
                        totalPayment = totalPayment + Double.valueOf(orderDetail.getPayment());
                        totalDiscountFee = totalDiscountFee + Double.valueOf(orderDetail.getDiscountFee());
                        totalAdjustFee = totalAdjustFee + Double.valueOf(orderDetail.getAdjustFee());

                        //保存订单明细
                        tanmaoOrderDetailMapper.add(orderInfo.getTid(),orderDetail.getOid(),orderDetail.getTitle()
                                ,orderDetail.getNumIid(),orderDetail.getSkuId(),orderDetail.getTotalQuantity()
                                ,orderDetail.getPrice(),orderDetail.getTotalFee(),orderDetail.getPayment()
                                ,orderDetail.getDiscountFee(),orderDetail.getAdjustFee()
                                ,orderDetail.getSkuPropertiesName(),new Date(),new Date());
                    }
                }

                int tanmaoOrderCount = tanmaoOrderMapper.findTanmaoOrderCount(orderInfo.getTid());
                if (tanmaoOrderCount == 0) {
                    //保存订单
                    tanmaoOrderMapper.add(orderInfo.getTid(), orderInfo.getStatus(), String.valueOf(totalQuantity), String.valueOf(totalFee),
                            String.valueOf(totalPayment), String.valueOf(totalDiscountFee), String.valueOf(totalAdjustFee), orderInfo.getCreated(),
                            orderInfo.getPayTime(), orderInfo.getReceiverName(), orderInfo.getReceiverState(), orderInfo.getReceiverAddress(),
                            orderInfo.getReceiverMobile(), new Date(), new Date());
                } else {
                    tanmaoOrderMapper.updateTanmaoOrderByTid(orderInfo.getStatus(),new Date(),orderInfo.getTid());
                }
            }
        }

        if (tanmaoTradesSoldGetResult.getHasNext()) {
            this.getTanmaoTradesSoldGet(orderStatus,currentPage + 1,sessionKey);
        }
    }

    @Override
    public void getTanmaoAllOrderInfo(String sessionKey) throws ApiException {
        //WAIT_SELLER_SEND_GOODS 等待卖家发货
        //WAIT_BUYER_CONFIRM_GOODS 等待买家确认收货
        //TRADE_BUYER_SIGNED 买家已签收（货到付款专用）
        //TRADE_FINISHED 交易成功

        //ALL_WAIT_PAY 所有买家未付款的交易
        //WAIT_BUYER_PAY 等待买家付款
        //TRADE_NO_CREATE_PAY 没有创建外部交易（支付宝交易）

        //ALL_CLOSED 所有关闭的交易
        //TRADE_CLOSED 交易关闭
        //TRADE_CLOSED_BY_TAOBAO 交易被淘宝关闭
        String[] status = {"ALL_WAIT_PAY","WAIT_SELLER_SEND_GOODS","WAIT_BUYER_CONFIRM_GOODS","TRADE_BUYER_SIGNED","TRADE_FINISHED","ALL_CLOSED"};

        for (int i = 0; i < status.length; i++) {
            this.getTanmaoTradesSoldGet(status[i],1L,sessionKey);
        }

    }

    @Override
    public void updateTanmaoItemQuantity(Long numIid, Long skuId, Long quantity, String sessionKey) throws ApiException {
        TaobaoClient client = new DefaultTaobaoClient(CommonUtils.SERVERURL, CommonUtils.APPKEY, CommonUtils.APPSECRET);
        ItemQuantityUpdateRequest req = new ItemQuantityUpdateRequest();
        req.setNumIid(numIid);
        req.setSkuId(skuId);
        req.setQuantity(quantity);
        req.setType(1L);

        ItemQuantityUpdateResponse rsp = client.execute(req, sessionKey);
    }

    @Override
    public void updateTanmaoDamirDomaItemQuantity(String sessionKey) throws ApiException {

        //查询天猫库存已扣，但ERP没有扣除的信息
        ArrayList<TamllOrder> tanmaoOrderList = tanmaoOrderMapper.findTanmaoOrderAllNoSync();

        HashMap<String, Integer> saleDataNumber = new HashMap<>();
        for (TamllOrder tamllOrder: tanmaoOrderList) {
            ArrayList<TamllOrderDetail> tamllOrderDetailList = tanmaoOrderDetailMapper.findTamllOrderDetailByTid(tamllOrder.getTid());

            for (TamllOrderDetail tamllOrderDetail: tamllOrderDetailList) {

                if (saleDataNumber.get(tamllOrderDetail.getSku_id()) != null) {
                    saleDataNumber.put(tamllOrderDetail.getSku_id(),tamllOrderDetail.getTotalQuantity() + saleDataNumber.get(tamllOrderDetail.getSku_id()));
                } else {
                    saleDataNumber.put(tamllOrderDetail.getSku_id(),tamllOrderDetail.getTotalQuantity());
                }
            }
        }

        ArrayList<TamllItem> tamllItems = tanmaoItemMapper.findAll();

        for (TamllItem tamllItem: tamllItems) {

            if (tamllItem.getProduct_skc() != null && tamllItem.getSpu() != null) {

                //查询该SPU的剩余库存
                long stockNumber = uniqueCodeProductMapper.findCurrentSizeCount(tamllItem.getSpu());

                Integer saleNoSubNumber = saleDataNumber.get(tamllItem.getSku_id());
                if (saleNoSubNumber != null) {
                    stockNumber = stockNumber - saleNoSubNumber;
                    if (stockNumber < 0) {
                        stockNumber = 0;
                    }
                }

                if (tamllItem.getLast_stock_number() == null || stockNumber != tamllItem.getLast_stock_number()) {
                    System.out.println("stockNumber = " + stockNumber);
                    tanmaoItemMapper.updateTmallItemStockNumber((int)stockNumber,tamllItem.getNum_iid(),tamllItem.getSku_id());
                    this.updateTanmaoItemQuantity(Long.valueOf(tamllItem.getNum_iid()),Long.valueOf(tamllItem.getSku_id()),stockNumber,sessionKey);
                }
            }
        }
    }

    @Override
    public List<List<Object>> getTanmaoInventoryInfo(String sessionKey) throws ApiException {
        List<Item> itemList = new ArrayList<>();

        long currentPage = 1;
        long totalPage = 1;
        long pageSize = 200;

        while (currentPage <= totalPage) {
            ItemsOnsaleGetResponse rsp = this.getTanmaoItemsOnsale(sessionKey,currentPage,pageSize);

            itemList.addAll(rsp.getItems());
            long l = rsp.getTotalResults();
            if (currentPage == 1) {
                totalPage = (long) Math.ceil((l * 1.0) / pageSize);
            }

            currentPage++;
        }

        long currentPageI = 1;
        long totalPageI = 1;
        long pageSizeI = 200;

        while (currentPageI <= totalPageI) {
            ItemsInventoryGetResponse rsp = this.getTanmaoItemsInventory(sessionKey, currentPageI, pageSizeI);

            itemList.addAll(rsp.getItems());
            long l = rsp.getTotalResults();
            if (currentPageI == 1) {
                totalPageI = (long) Math.ceil((l * 1.0) / pageSizeI);
            }

            currentPageI++;
        }

        List<List<Object>> rows = new ArrayList();

        for (Item item : itemList) {
            ItemSkusGetResponse tanmaoItemSkus = this.getTanmaoItemSkus(String.valueOf(item.getNumIid()), sessionKey);
            List<Sku> skus = tanmaoItemSkus.getSkus();

            for (Sku sku: skus) {
                List<Object> row = new ArrayList();

                row.add(item.getPicUrl());
                row.add(item.getNumIid());
                row.add(sku.getSkuId());

                TanmaoItem tanmaoItemByNumiidAndSkuid = tanmaoItemMapper.findTanmaoItemByNumiidAndSkuid(String.valueOf(item.getNumIid()), String.valueOf(sku.getSkuId()));

                row.add(tanmaoItemByNumiidAndSkuid.getProductSkc());
                row.add(tanmaoItemByNumiidAndSkuid.getSpu());
                row.add(item.getTitle());

                String propertiesName = sku.getPropertiesName();

                String[] nameValue = propertiesName.split(";");
                boolean colorFlag = false;
                boolean sizeFlag = false;
                for (String valueStr : nameValue) {
                    String[] value = valueStr.split(":");

                    if ("颜色".equals(value[2]) || "颜色分类".equals(value[2]) || value[2].contains("颜色")) {
                        colorFlag = true;
                        row.add(value[3]);
                    }
                }

                for (String valueStr : nameValue) {
                    String[] value = valueStr.split(":");

                    if ("尺码".equals(value[2]) || "尺寸".equals(value[2])) {
                        sizeFlag = true;
                        row.add(value[3]);
                    }
                }

                if (!colorFlag) {
                    row.add("");
                }
                if (!sizeFlag) {
                    row.add("");
                }

                row.add(sku.getPrice());
                row.add(sku.getQuantity());
                rows.add(row);
            }
        }

        return rows;
    }
}
